package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.uitls.MD5Util;
import com.example.forum.uitls.StringUtil;
import com.example.forum.uitls.UUIDUtil;
import com.sun.istack.internal.NotNull;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NotNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NotNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NotNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NotNull String passwordRepeat){
        if(!password.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.fail(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        User user=new User();
        user.setUsername(username);
        user.setNickname(nickname);
        String salt=UUIDUtil.UUID_32();
        String encryptPassword=MD5Util.md5Salt(password,salt);
        user.setPassword(encryptPassword);
        user.setSalt(salt);
        userService.createNormalUser(user);
        return AppResult.success();
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") @NotNull String username,
                           @ApiParam("密码") @RequestParam("password") @NotNull String password){
        User user=userService.login(username,password);
        if(user==null){
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.fail(ResultCode.FAILED_LOGIN);
        }
        AppConfig.setUser(request,user);
        return AppResult.success();
    }

    @ApiOperation("用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @ApiParam("用户id") @RequestParam(value = "id",required = false) Long id){
        if(id==null){
            id=AppConfig.getUser(request).getId();
        }
        User user=userService.selectById(id);
        if(user==null){
            return AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }

    @ApiOperation("退出系统")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        AppConfig.removeUser(request);
        return AppResult.success("退出成功");
    }

    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("用户名") @RequestParam(value = "username",required = false) String username,
                                @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender,
                                @ApiParam("邮箱") @RequestParam(value = "email",required = false) String email,
                                @ApiParam("电话号码") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @ApiParam("个人简介") @RequestParam(value = "remark",required = false) String remark){
        if(StringUtil.isEmpty(username)
                &&StringUtil.isEmpty(nickname)
                &&StringUtil.isEmpty(email)
                &&gender==null
                &&StringUtil.isEmpty(phoneNum)
                &&StringUtil.isEmpty(remark)){
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        User user=AppConfig.getUser(request);

        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setEmail(email);
        updateUser.setGender(gender);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);
        userService.modifyInfo(updateUser);

        user=userService.selectById(user.getId());
        AppConfig.setUser(request,user);

        return AppResult.success(user);
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPwd(HttpServletRequest request,
                               @ApiParam("原密码") @RequestParam("oldPassword") @NotNull String oldPassword,
                               @ApiParam("新密码") @RequestParam("newPassword") @NotNull @org.jetbrains.annotations.NotNull String newPassword,
                               @ApiParam("确认密码") @RequestParam("passwordRepeat") @NotNull String passwordRepeat){
        if(!newPassword.equals(passwordRepeat)){
            log.error(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.fail(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        HttpSession session=request.getSession(false);
        User user=(User)session.getAttribute(AppConfig.SESSION_KEY);

        userService.modifyPassword(user.getId(),newPassword,oldPassword);
        AppConfig.removeUser(request);
        return AppResult.success();
    }
}
